<template>
  <div class="absolute inset-0 p-2">
    <div class="h-full flex flex-col">
      <div class="flex flex-wrap gap-2 mt-2 mb-2">
        <div v-for="col in columnDefs" :key="col.field" class="w-32">
          <el-input
            v-model="searchTerms[col.field]"
            size="small"
            :placeholder="`搜索` + col.headerName"
            @input="onColumnSearch(col.field)"
          />
        </div>
      </div>
      <div class="flex-1">
        <ag-grid-vue
          class="ag-theme-alpine"
          style="width: 100%; height: 100%"
          :row-data="tableData"
          :column-defs="columnDefs"
          :grid-options="gridOptions"
          @gridReady="onGridReady"
        >
        </ag-grid-vue>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import moment from 'moment'
import Vue from 'vue'
import { mapState, mapActions } from 'vuex'
import { hongkongDataMap, macauDataMap } from '@/data/index.js'
import {
  ROUTER_MAP,
  getPredictionResults,
  getMacauNextDay,
  getHongKongNextDay,
  getSeriesForPast,
  getSeriesForLineTypeTwo,
  getMoneyText,
  getMantissa,
} from '@/utils/study.js'

import { AgGridVue } from 'ag-grid-vue'

import CustomCellRenderer from './components/CustomCellRenderer.vue'
import ActionCellRenderer from '@/views/kit/components/ActionCellRenderer.vue'
import AccurateCellRenderer from './components/AccurateCellRenderer.vue'
import LuckyCellRenderer from './components/LuckyCellRenderer.vue'
import KillCellRenderer from './components/KillCellRenderer.vue'

import 'ag-grid-community/styles/ag-grid.css' // 基础样式
import 'ag-grid-community/styles/ag-theme-alpine.css' // 主题样式
// 垂直居中样式
const verticalCenterStyle = { display: 'flex', alignItems: 'center' }

// 定义魔法数字常量
const VALUE_RED = 0
const VALUE_GREEN = 10

// 计算 arbitrary 模块的统计数据
const calcArbitrary = (allValues, groupMapBySize) => {
  // 将所有分组映射扁平化为一个单一对象
  const flattenedGroupMap = Object.assign({}, ...Object.values(groupMapBySize))
  // console.log('flattenedGroupMap', flattenedGroupMap) // key 是对应数值的所有分组字符串名称, value 是对应分组数据

  // 提取每种组大小对应的分组选项
  const groupOptions = Object.entries(groupMapBySize).reduce((acc, [size, groups]) => {
    acc[size] = Object.keys(groups)
    return acc
  }, {})

  // console.log('groupOptions', groupOptions) // key 是英文数值, value 是对应数值的所有分组字符串名称数组

  // 初始化结果数组
  const results = {
    redContinuousMax: [],
    greenRebound: [],
    greenContinuous: []
  }

  // console.log('Object.entries(groupOptions)', Object.entries(groupOptions))

  const entriesGroupOptions = Object.entries(groupOptions) // 数组: first 是英文数值, last 是对应数值的所有分组字符串名称数组

  // 遍历每种组大小及其对应的分组
  entriesGroupOptions.forEach(([sizeKey, groups]) => {
    groups.forEach((groupName) => {
      const groupData = flattenedGroupMap[groupName]
      const processedValues = getSeriesForLineTypeTwo(allValues, groupData)

      // 获取最后两个元素
      const [secondLast, last] = processedValues.slice(-2)
      const lastRed = BigInt(last.valueCount[VALUE_RED])
      const lastGreen = BigInt(last.valueCount[VALUE_GREEN])

      // console.log('lastRed', lastRed.toString())
      // console.log('lastGreen', lastGreen.toString())

      // 计算总数并验证
      const totalCount = lastRed + lastGreen
      if (totalCount === 0n) {
        console.warn('Total count is zero, skipping calculation for group:', groupName)
        return
      }

      // 计算正确率
      const accuracyRate = Number((lastGreen * 100n) / totalCount).toFixed(2)

      // 创建最后一项对象
      const lastItem = {
        group: groupName,
        router: ROUTER_MAP[groupName],
        last,
        groupsNumber: last.groupsNumber,
        maxCountError: last.maxWrongStreak,
        accuracyRate
      }

      // 根据最后两个值确定描述
      if (last.value === VALUE_RED && secondLast.value === VALUE_RED) {
        lastItem.a_desc = '预测红色连续不超过2次'
        results.redContinuousMax.push(lastItem)
      } else if (last.value === VALUE_RED && secondLast.value === VALUE_GREEN) {
        lastItem.a_desc = '预测绿色回弹，红色不连续'
        results.greenRebound.push(lastItem)
      } else if (last.value === VALUE_GREEN && secondLast.value === VALUE_RED) {
        lastItem.a_desc = '预测绿色连续'
        results.greenContinuous.push(lastItem)
      }
    })
  })

  // 定义排序函数：先按 accuracyRate 降序，再按 maxCountError 升序
  const sortResults = (a, b) => {
    if (b.accuracyRate !== a.accuracyRate) {
      return b.accuracyRate - a.accuracyRate // accuracyRate 降序
    }
    return a.maxCountError - b.maxCountError // maxCountError 升序
  }

  // 对结果数组进行排序
  results.redContinuousMax.sort(sortResults)
  results.greenRebound.sort(sortResults)
  results.greenContinuous.sort(sortResults)

  // 统一打印所有结果，便于调试和查看
  // console.log('红色连续不超过2次:', results.redContinuousMax)
  // console.log('绿色回弹，红色不连续:', results.greenRebound)
  // console.log('绿色连续:', results.greenContinuous)
  return results
}

// 计算 past  模块的统计数据
const calcPast = (allValues, _selectValue) => {
  const past_results = getSeriesForPast(allValues, _selectValue)
  const last_item = past_results[past_results.length - 1]
  const result = _.cloneDeep(last_item.recentValues)
  result.push(last_item.sourceData.number)
  return result
}

/**
 * 处理控制台输出
 * @param {string} nextDay - 下期日期
 * @param {object} arbitrary_results - 任意模块的统计数据
 * @param {object} last_item - 最后一条数据
 */
const handleConsole = (nextDay, arbitrary_results, last_item, past_results, label) => {
  const text = `
  ${label}

  ${nextDay}
	TODO：
	${getMoneyText(arbitrary_results.redContinuousMax, '红色连续不超过2次')}

	${getMoneyText(arbitrary_results.greenRebound, '绿色回弹，红色不连续')}

	${getMoneyText(arbitrary_results.greenContinuous, '绿色连续')}

  kill mantissa:
    [
      ${getMantissa(last_item.number).join(',')}
    ]

  前${past_results.length}期：
    [
      ${past_results.join(',')}
    ]

  kill all：
    [

    ]
  `
  // console.clear()
  console.log(text)
}

export default {
  name: 'ForecastPage',
  components: {
    AgGridVue,
    // eslint-disable-next-line vue/no-unused-components
    CustomCellRenderer,
    // eslint-disable-next-line vue/no-unused-components
    ActionCellRenderer,
    // eslint-disable-next-line vue/no-unused-components
    AccurateCellRenderer,
    // eslint-disable-next-line vue/no-unused-components
    LuckyCellRenderer,
    // eslint-disable-next-line vue/no-unused-components
    KillCellRenderer
  },
  data() {
    return {
      // 原始数据
      originalData: [],
      // 加载器
      loading: true,
      // 保存每列的搜索关键字
      searchTerms: {},
      // 列
      columnDefs: [
        // 设置单元格垂直居中
        {
          headerName: 'Date',
          field: 'time',
          width: 128,
          sort: 'desc',
          cellStyle: verticalCenterStyle
        },
        {
          headerName: 'Special',
          field: 'number',
          width: 128,
          cellStyle: verticalCenterStyle
        },
        {
          headerName: 'Accurate',
          field: 'isAccurate',
          width: 128,
          cellStyle: verticalCenterStyle,
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(AccurateCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        },
        {
          headerName: 'kill Groups',
          field: 'killGroups',
          width: 430,
          cellStyle: verticalCenterStyle,
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(KillCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        },
        {
          headerName: 'Lucky',
          field: 'luckyNumbers',
          width: 860,
          cellStyle: verticalCenterStyle,
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(LuckyCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        },

        {
          // 添加操作栏
          headerName: 'Action',
          field: 'actions',
          // 设置操作栏宽度
          width: 128,
          // 固定列到右侧
          pinned: 'right',
          cellStyle: verticalCenterStyle,
          cellRenderer: (params) => {
            const vm = new Vue({
              render(h) {
                return h(ActionCellRenderer, {
                  props: { params }
                })
              }
            }).$mount()
            return vm.$el
          }
        }
      ],
      // 表格配置
      gridOptions: {
        // 允许单元格文本选择
        enableCellTextSelection: true,
        // 行高
        rowHeight: 84,
        // 默认布局，允许滚动条
        domLayout: 'normal'
      },

      // 表格数据
      tableData: [],

      // 表格数据备份
      tableDataCopy: []
    }
  },
  computed: {
    // 地区
    ...mapState('study', ['region', 'globalGroupMapBySize']),
    // 全量数据备份
    allValuesCopy() {
      let values = []
      if (this.region === 'hk') {
        values = Object.values(hongkongDataMap).flat()
      } else {
        values = Object.values(macauDataMap).flat()
      }

      console.log('values.length', values.length)

      // todo cyan task: 移除 slice
      // values = values.slice(0, 1000)
      // console.log('todo remove slice, values:', values)
      return values
    }
  },

  watch: {
    region() {
      this.initTableData()
    }
  },

  created() {
    // 初始化表格数据
    this.initTableData()
    // 初始化搜索关键字
    this.initializeSearchTerms()
  },
  methods: {
    ...mapActions('study', ['setGlobalGroupMapBySize']),

    // 网格表格初始化事件
    onGridReady(params) {
      this.gridApi = params.api
      this.gridColumnApi = params.columnApi

      // 调整列宽以适应容器
      // this.gridApi.sizeColumnsToFit()

      // console.log('gridApi', this.gridApi)

      // 窗口大小变化时调整表格宽度
      // window.addEventListener('resize', () => {
      //   this.gridApi.sizeColumnsToFit()
      // })
    },

    // 初始化搜索关键字
    initializeSearchTerms() {
      this.columnDefs.forEach((col) => {
        if (col.field) {
          this.$set(this.searchTerms, col.field, '') // 初始化每列搜索关键字为空
        }
      })
    },

    // 列搜索事件
    onColumnSearch(field) {
      const filteredData = this.tableDataCopy.filter((item) => {
        return Object.keys(this.searchTerms).every((key) => {
          const searchValue = this.searchTerms[key].trim().toLowerCase()
          return !searchValue || (item[key] && item[key].toString().toLowerCase().includes(searchValue))
        })
      })
      this.tableData = filteredData
    },

    // 计算
    async calc() {
      // 获取下期日期
      let nextDay

      const label = this.region === 'm' ? '澳门' : '香港'

      // console.log(store.state.study.region)
      // 获取最后一条数据
      const last_item = this.tableDataCopy.slice(-1)[0]

      // 获取下期日期
      if (this.region === 'm') {
        nextDay = getMacauNextDay(last_item.time)
      } else {
        nextDay = await getHongKongNextDay()
      }

      // 计算任意模块的统计数据
      const arbitrary_results = calcArbitrary(this.allValuesCopy, this.globalGroupMapBySize)
      // console.log('arbitrary_results', arbitrary_results)

      // // 计算 Past 模块的统计数据
      const past_results = calcPast(this.allValuesCopy, 10)
      // console.log('past_results', past_results)

      // // 处理控制台输出
      handleConsole(nextDay, arbitrary_results, last_item, past_results, label)
    },

    // 初始化表格数据
    async initTableData() {
      // console.log('this.globalGroupMapBySize', this.globalGroupMapBySize)
      // groupMap and Request
      this.tableDataCopy = _.cloneDeep(getPredictionResults(this.allValuesCopy))
      this.tableData = _.cloneDeep(this.tableDataCopy)

      this.calc()
    }
  }
}
</script>
